package cn.jdemo.juc.highquality.rpc_brief.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class RpcServerProxy {
	
	private IHello hello = new HelloService();
	
	/**
	 * 服务发布
	 * @throws ClassNotFoundException 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws IOException 
	 */
	public void publishServer() throws ClassNotFoundException, NoSuchMethodException,
			SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			while (true) {
				Socket socket = serverSocket.accept();
				InputStream inputStream = socket.getInputStream();
				ObjectInputStream oInputStream = new ObjectInputStream(inputStream);
				
				String methodName = oInputStream.readUTF();
				Object[] objs = (Object[]) oInputStream.readObject();
				
				Class<?>[] types = new Class[objs.length];
                for (int i = 0; i < types.length; i++) {
                    types[i] = objs[i].getClass();
                }
				Method method = IHello.class.getMethod(methodName, types);
				
				Object returnObj = method.invoke(hello, objs);
				ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
				oos.writeObject(returnObj);
                oos.flush();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
